<template>
    <div id="report-view">
        <a-row class="filters">
            <a-col span="18">
              <a-range-picker format="YYYY-MM-DD" :default-value="dateValue"  v-on:change="changeDate" style="width: 230px"></a-range-picker>
              <a-button v-on:click="query" :loading="loading" type="primary" style="margin-left: 5px">查询</a-button>
            </a-col>
            <a-col span="6" class="chart-filters">
                <div style="float: right">
                    <a-select v-model="chartType" placeholder="图表类型" style="width:100px">
                        <a-select-option v-for="item in chartTypes" :value="item.value" :key="item.value">{{ item.label }}</a-select-option>
                    </a-select>
                </div>
            </a-col>
        </a-row>
        <a-row class="chart-filters">
          <a-spin :spinning="loading">
            <div id="chart" class="echarts"></div>
          </a-spin>
        </a-row>
        <a-divider />
        <a-row>
            <a-col span="24">
                <a-table
                  ref="table"
                  :loading="loading"
                  :columns="table.columns"
                  :data-source="table.data"
                  :pagination="pagination"
                  rowKey="id"
                  @change="onTableChange"
                  border>
                  <div slot="expandedRowRender" slot-scope="record" style="margin: 0">
                    <a-row class="expand-row">
                      <a-col span="8">
                        <span class="expand-key">设备型号: </span>
                        <span class="expand-value">{{ record.model }}</span>
                      </a-col>
                      <a-col span="8">
                        <span class="expand-key">操作系统: </span>
                        <span class="expand-value">{{ record.os }}</span>
                      </a-col>
                      <a-col span="8">
                        <span class="expand-key">操作系统版本: </span>
                        <span class="expand-value">{{ record.os_version }}</span>
                      </a-col>
                    </a-row>
                    <a-row>
                      <a-col span="8">
                        <span class="expand-key">浏览器: </span>
                        <span class="expand-value">{{ record.browser }}</span>
                      </a-col>
                      <a-col span="8">
                        <span class="expand-key">来源: </span>
                        <span class="expand-value">{{ record.utm_source }}</span>
                      </a-col>
                      <a-col span="8">
                        <span class="expand-key">所在城市: </span>
                        <span class="expand-value">{{ record.city }}</span>
                      </a-col>
                    </a-row>
                  </div>

                  <template slot="action" slot-scope="text, record">
                    <span>
                      {{ getEventDisplayName(record.event) }}
                    </span>
                  </template>
                </a-table>
                <div style="margin: 10px;overflow: hidden">
                    <div style="float: right;">
              </div>
                </div>
            </a-col>
        </a-row>
    </div>
</template>

<script>
import {getDay} from "@/utils/util";
import {getEventsApi} from "@/api/analyseType";
import {getUserDetailActionsApi} from "@/api/userDetails";
export default {
  name: "UserEventReport",
  components: {},
  props: {
    userId: String,
    groupId: Number,
    datasourceId: Number,
  },
  data: function () {
    return {
      loading: false,
      chartTypes: [{
        label: '柱状图',
        value: 'bar'
      }, {
        label: '折线图',
        value: 'line'
      }
      ],
      dateValue: [this.moment(getDay(-7)).format('YYYY-MM-DD'), this.moment(getDay(-1)).format('YYYY-MM-DD')],
      chartType: 'line',
      chart: {
        eventChart: null,
      },
      table: {
        columns: [
          {
            title: '时间',
            dataIndex: 'createstamp',
            width: 300,
          },
          {
            title: '事件',
            dataIndex: 'event',
            scopedSlots: {customRender: 'action'},
          },

        ],
        data: [],
      },
      pagination:{
        current : 1,
        pageSize: 10,
        total: 0,
        pageSizeOptions: ['10', '30', '50', '100'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal : (total)=>{
          return `共  ${total}  条记录   第  ${this.pagination.current} / ${Math.ceil(this.pagination.total/this.pagination.pageSize)}  页 `
        }
      },
      pager: {
        data: [],
        current: 1,
        size: 20
      },
      event: {
        trend: [],
        detail: [],
        pv: 0
      },
      events: [],
      time: {
        start: getDay(-7),
        end: getDay(-1),
        unit: 'day',
      },
    }
  },
  methods: {
    changeDate: function(dateValue) {
      this.time.start = dateValue[0].format('YYYY-MM-DD');
      this.time.end = dateValue[1].format('YYYY-MM-DD');
    },
    getChartOptions: function() {
      return {
        title: {
          text: ''
        },
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '3%',
          containLabel: true
        },
        legend: {
          data:[]
        },
        toolbox: {
          feature: {
          }
        },
        xAxis: {
          type: 'category',
          data: []
        },
        yAxis: {
          type: 'value'
        },
        series: []
      };
    },
    getEventDisplayName: function(eventName) {
      let eventDisplayName = eventName;
      for(let i = 0; i < this.events.length; i++) {
        if(this.events[i].name === eventName) {
          eventDisplayName = this.events[i].displayName;
          break;
        }
      }
      return eventDisplayName;
    },
    updateChart: function() {
      switch(this.chartType) {
        case "line":
          this.updateLineChart();
          break;
        case "bar":
          this.updateBarChart();
          break;
      }
    },
    updateLineChart: function() {
      let options = this.getChartOptions();
      let obj = {};
      options.legend.data.push('事件次数');
      let seriesData = [];
      for(let i = 0; i < this.event.trend.length; i++) {
        let label = this.event.trend[i].date;
        if(!obj[label]) {
          options.xAxis.data.push(label);
          obj[label] = true;
        }
        seriesData.push(this.event.trend[i].count);
      }
      options.series.push({
        name: '事件次数',
        type: 'line',
        smooth: true,
        data: seriesData
      });
      this.chart.eventChart.setOption(options, true);
      this.chart.eventChart.resize();
    },
    updateBarChart: function() {
      let options = this.getChartOptions();
      let obj = {};
      options.legend.data.push('事件次数');
      let seriesData = [];
      for(let i = 0; i < this.event.trend.length; i++) {
        let label = this.event.trend[i].date;
        if(!obj[label]) {
          options.xAxis.data.push(label);
          obj[label] = true;
        }
        seriesData.push(this.event.trend[i].count);
      }
      options.series.push({
        name: '事件次数',
        type: 'bar',
        smooth: true,
        data: seriesData
      });
      this.chart.eventChart.setOption(options, true);
      this.chart.eventChart.resize();
    },
    setTableData (){
      if (!this.event || !this.event.detail || this.event.detail.length < 1){
        this.table.data = []
        return
      }
      const start = (this.pagination.current - 1) * this.pagination.pageSize
      const last = start + this.pagination.pageSize
      const end = last >= this.pagination.total ? this.pagination.total : last
      this.table.data = this.event.detail.slice(start, end)
    },
    onTableChange (page) {
      this.pagination.current = page.current
      this.pagination.pageSize = page.pageSize
      this.setTableData()
    },
    query: function () {
      this.loading = true;
      getUserDetailActionsApi(this.userId, {groupId:this.groupId}, this.time).then(response => {
        if (response.code === 0) {
          this.event = response.data;
          this.pagination.total = response.data.detail.length
          this.updateChart();
          this.setTableData();
        }
      }).catch(error => {
        console.log(error);
      }).finally(() => {
        this.loading = false;
      });
    },
    getEventList: function() {
      getEventsApi({ id: this.datasourceId }).then(response => {
        if (response.code === 0) {
          this.events = response.data;
        }
      }).catch(error => {
        console.log(error);
      });
    },
  },
  watch: {
    chartType: function () {
      this.updateChart();
    }
  },
  mounted() {
    this.getEventList();
    this.chart.eventChart = this.$echarts.init(document.getElementById('chart'), 'light');
    window.onresize = () => {
      this.chart.eventChart.resize();
    }
    this.query();
  }
}

</script>

<style scoped>
    .filters {
        margin-bottom: 10px;
    }
    .table-actions {
        margin-bottom: 10px;
    }
    .echarts {
      height: 400px;
    }
    .demo-spin-icon-load{
        animation: ani-demo-spin 1s linear infinite;
    }
</style>
